import sys
import traceback
from PySide6.QtWidgets import * # type: ignore
from PySide6.QtCore import * # type: ignore
from PySide6.QtGui import * # type: ignore
from qfluentwidgets import *  # type: ignore

from gui.island import Island
from utils import cfg_util, windows_util

def handleException(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
    
    QMessageBox.critical(None, 'Fatal Error', f'An unexpected error has occurred:\n'
                                  f'{traceback.print_exception(exc_type, exc_value, exc_traceback)}')
    
    exit(1)

sys.excepthook = handleException

# Entry point of the application
if __name__ == '__main__':
    # Load configuration settings
    cfg_util.loadConfig()
    
    # Check if running with administrator privileges
    if windows_util.isAdminMode():
        # Start application with admin rights
        app = QApplication([])
        setTheme(Theme.DARK)  # Set dark theme
        main_window_instance = Island()  # Create main window
        sys.exit(app.exec())  # Start event loop
    else:
        # Check if user explicitly requested non-admin mode
        if '--island-no-admin' in sys.argv:
            # Start application without admin rights
            app = QApplication([])
            setTheme(Theme.DARK)
            main_window_instance = Island()
            sys.exit(app.exec())
        else:
            # Handle admin privilege preference
            if cfg_util.config_instance.admin_launch == 'Unknown':
                # First time running - ask user for preference
                app = QApplication([])

                # Get the api key
                dialog = QInputDialog.getText(None, 'API Key', 'Enter youe DeepSeek API key here.\nAnd you can you the AI functions!(Press Shift+Alt+Z to input prompt)')
                if dialog[1]:
                    cfg_util.config_instance.api_key = dialog[0]
                    cfg_util.saveConfig()
                else:
                    exit(0)
                
                # Create dialog to ask about admin privileges
                dialog = QMessageBox()
                dialog.setWindowTitle('Administrator Privileges')
                dialog.setText('Sorry, but this application requires administrator privileges to get stronger pin to top effect! (or you still can use it without admin rights, but the pin to top effect is weaker)\n\nDo you want to restart the application with administrator privileges?')
                dialog.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No | QMessageBox.StandardButton.NoToAll | QMessageBox.StandardButton.YesToAll)
                result = dialog.exec()
                
                # Handle user choice
                if result == QMessageBox.StandardButton.Yes:
                    windows_util.restartAsAdmin()  # Restart with admin rights
                elif result == QMessageBox.StandardButton.No:
                    windows_util.restartWithoutAdmin()  # Restart without admin rights
                elif result == QMessageBox.StandardButton.NoToAll:
                    # Remember choice: never use admin rights
                    cfg_util.config_instance.admin_launch = False
                    cfg_util.saveConfig()
                    windows_util.restartWithoutAdmin()
                elif result == QMessageBox.StandardButton.YesToAll:
                    # Remember choice: always use admin rights
                    cfg_util.config_instance.admin_launch = True
                    cfg_util.saveConfig()
                    windows_util.restartAsAdmin()
            elif cfg_util.config_instance.admin_launch == True:
                # User previously chose to always use admin rights
                windows_util.restartAsAdmin()
            else:
                # User previously chose to never use admin rights
                windows_util.restartWithoutAdmin()